import React from 'react'
import './index.css'
import PubSub from 'pubsub-js'
import { Button, Col, Row,Popover  } from 'antd';
import {UnorderedListOutlined, StepBackwardOutlined, StepForwardOutlined, PauseOutlined, CaretRightOutlined ,CloseOutlined} from '@ant-design/icons'
import axios from 'axios';
import store from '../../redux/store';
export default function Player() {
  const [isPlay, setIsPlay] = React.useState(false)
  //进度条比率
  const [rate, setRate] = React.useState(0)
  //播放总时长
  const [totaltTime,setTotalTime] = React.useState(0)
  //播放总时间戳
  const [duration, setDuration] = React.useState(0)
  //现在时间
  const [currentTime,setCurrentTime] = React.useState(0)
  //歌名
  const [songTitle,setSongTitle] = React.useState('')
  //歌词
  const [lyr,setLyr]=React.useState([])
  const [nowLyr,setNowLyr]=React.useState()
  const [playSrc,setPlaySrc]=React.useState('')
  //现在播放的索引
  const[nowPlayIndex,setNowPlayIndex]=React.useState(0)
  //播放列表
  const [playList,setPlayList]=React.useState(store.getState())
  const [visible, setVisible] =React.useState(false);
  const player = React.useRef()
//播放单曲
store.subscribe(()=>{
  setPlayList(store.getState())
})
  React.useEffect(()=>{
    function mySub(msg,data){
      //console.log(data);
          let url=`http://localhost:3000/getMusicPlay?songmid=${data.mid}`;
          axios.get(url).then(
            (res)=>{
              // console.log(res);//获取播放地址
              if(res.data.data.playUrl[data.mid].error){
                alert(res.data.data.playUrl[data.mid].error)
              return ;
              }
              setNowPlayIndex(0)
              setPlaySrc(res.data.data.playUrl[data.mid].url)
              setSongTitle(data.name)
              store.dispatch({type:"add",data:{mid:data.mid,name:data.name}})//能播放的同时加入到播放列表
            }
          )
          axios.get(`http://localhost:3000/getLyric?songmid=${data.mid}&isFormat=true`).then(
            (res)=>{
              setLyr(res.data.response.lyric.lines)
            }
          ) 
    }    
    const token=PubSub.subscribe('getPlayUrl',mySub)
    return ()=>{
      PubSub.unsubscribe(token)
    }
})
//播放器时间显示 
function getTime(time){
    let m=Math.floor(time/60)
    let s=Math.floor(time-60*m)
    return `${m}:${s>=10?s:"0"+s}`
}

  function handlePlay() {
    if (isPlay){
      player.current.pause()
    }
    else{
      player.current.play()
    }
    setIsPlay(!isPlay)
  }
  function playerInit(){
    setIsPlay(true)
    setTotalTime(getTime(player.current.duration))
    setDuration(player.current.duration?player.current.duration:0)
    setNowLyr(undefined)
  }
  function playerFresh(){
    setRate(player.current.currentTime*100/duration)
    setCurrentTime(getTime(player.current.currentTime))
    let y=lyr.filter((l)=>parseInt(l.time/1000)<=parseInt(player.current.currentTime));
   setNowLyr(<div>{y[y.length-2].txt}<br/><span style={{color:'#1ecd99',fontSize:'18px'}}>{y[y.length-1].txt}</span></div>)
  }
  function progress(e){
    console.log(e.clientX);
    console.log(e);
    let r=(e.clientX-512)/10.8
    console.log(r);
    player.current.currentTime=r*duration/100
    setRate(r)
  }
function prevSong(){
  let now=nowPlayIndex
  if(nowPlayIndex==0){
   now=playList.length
  }
  let song=playList[now-1]
  toPlay(song.mid,song.name)
  now=now-1;
  setNowPlayIndex(now)
}
function nextSong(){
  let now=nowPlayIndex
  if(nowPlayIndex==playList.length-1){
   now=-1
  }
  let song=playList[now*1+1]
  toPlay(song.mid,song.name)
  now=now*1+1;
  setNowPlayIndex(now)
}
function toPlay(mid,name){
  let url=`http://localhost:3000/getMusicPlay?songmid=${mid}`;
  axios.get(url).then(
    (res)=>{
      // console.log(res);//获取播放地址
      if(res.data.data.playUrl[mid].error){
        alert(res.data.data.playUrl[mid].error)
      return ;
      }
      setPlaySrc(res.data.data.playUrl[mid].url)
      setSongTitle(name)
      setNowPlayIndex(playList.findIndex((m)=>m.mid==mid))
    }
  )
  axios.get(`http://localhost:3000/getLyric?songmid=${mid}&isFormat=true`).then(
    (res)=>{
      setLyr(res.data.response.lyric.lines)
    }
  ) 
}
  const handleVisibleChange = () => {
    setVisible(!visible);
  }

  let list=playList.map((l)=>{
    return (
      <li key={l.mid} onClick={()=>toPlay(l.mid,l.name)
      }>{l.name}<CloseOutlined style={{float:"right",marginTop:"5px"}} onClick={(e)=>{
        e.stopPropagation()
        store.dispatch({type:"rem",data:{mid:l.mid?l.mid:l.songmid}}) 
      }}/></li>
    )
   
  })
 
  return (
    <div className='player'>
      <div className="progress"onClick={progress}>
        <div  style={{backgroundColor:'green',height:'100%',width:rate+"%"}}></div>
      </div>
      <Row>
      <Col span={6} >
            {/* <img src='' alt='图' width="55px" height="55px" />   获取图片的API失效 */}
            <span  style={{fontSize:"16px"}}>{songTitle}</span>
      </Col>
        <Col span={4} >
          <Button shape="circle" size="large"><StepBackwardOutlined onClick={prevSong} /></Button>
          <Button shape="circle" size="large" onClick={handlePlay}>{isPlay ? <PauseOutlined /> : <CaretRightOutlined />}
          </Button>
          <Button shape="circle" size="large"><StepForwardOutlined  onClick={nextSong}  /></Button>
        </Col>
        <Col span={8} offset={2}>
          {nowLyr}
        </Col>
        <Col span={2}>
            <span style={{fontSize:"20px"}}>{currentTime}/{totaltTime}</span>
      </Col>
      <Col span={2}>
      <Popover
        content={<ul className='playlist'>{list}</ul>}
        title="PlayList"
        trigger="click"
        visible={visible}
        onVisibleChange={handleVisibleChange}
      >
         <Button shape="circle" size="large"><UnorderedListOutlined /></Button>
      </Popover>
         </Col>
      </Row>
      <audio src={playSrc} ref={player} autoPlay onCanPlay={playerInit} onTimeUpdate={playerFresh} onEnded={nextSong}></audio>
    </div>
  )
}
